import fs from 'fs';
import path from 'path';
import multer from '@koa/multer';
import { saveOnline } from './resume.service';
import { ResumeEntity } from '../entity/resume.entity';

const basePath = 'public/upload';
/**
 * 上传文件
 * @param file
 * @returns
 */
export async function uploadFile(uid: string, file: multer.File) {
  try {
    const time = new Date().getTime().toString();
    const suffix = '.' + file.mimetype.split('/')[1];
    const filePath = path.resolve(basePath, time + suffix);
    const resume = new ResumeEntity();
    resume.name = file.originalname.split('.')[0];
    resume.file = `/file/download/${time + suffix}`;
    resume.type = 1;
    resume.uid = uid;
    const index = await saveOnline(resume);
    if (index == 1) {
      fs.writeFileSync(filePath, file.buffer);
      return true;
    }
    return false;
  } catch (error) {
    console.log(error);
    return false;
  }
}

/**
 * 下载文件
 * @param filename
 * @returns
 */
export async function downloadFile(filename: string) {
  try {
    const filePath = path.resolve(basePath, filename);
    const content = fs.readFileSync(filePath);
    return content;
  } catch (error) {
    console.log(error);
    return false;
  }
}
